package server.app.fileupload;

import java.io.File;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import org.apache.commons.lang.StringUtils;

public class ImgCompress implements Runnable
{
    final static int procNum = Runtime.getRuntime().availableProcessors();
    static int maxNum = 10;
    File parentDirectory;
    Resource res;

    public ImgCompress(File imageRootDrictory, Resource resource)
    {
        this.parentDirectory = imageRootDrictory;
        this.res = resource;
    }

    ExecutorService service = Executors.newFixedThreadPool(procNum * 2 - 1);

    public void run()
    {
        LinkedList<String> imgNameList = res.getResource();
        if (maxNum * 2 + 1 < imgNameList.size())
        {
            maxNum++;
        }
        else if (maxNum < 10)
        {
            maxNum = 10;
        }

        ArrayList<Future<String>> targetList = new ArrayList<Future<String>>();

        int i = maxNum;
        while (!imgNameList.isEmpty())
        {
            if (i == 0)
            {
                break;
            }
            else
            {
                i--;
            }
            String fileName = imgNameList.poll();
            if (StringUtils.isBlank(fileName))
            {
                continue;
            }

            File imgFile = new File(parentDirectory, fileName);

            Future<String> f = service.submit(new SingleImgCompress(parentDirectory, imgFile));
            targetList.add(f);
        }
        int index = 0;
        for (; targetList.size() > 0 && index > targetList.size() - 1;)
        {
            Future<String> f = targetList.get(index);
            if (f.isDone() || f.isCancelled())
            {
                index++;
                try
                {
                    String rebackFileName = f.get();
                    // We dont need the return value,and next step need add the time limit.
                    if (StringUtils.isNotBlank(rebackFileName))
                    {
                        // addImage(rebackFileName);
                    }
                }
                catch (InterruptedException e)
                {
                    e.printStackTrace();
                }
                catch (ExecutionException e)
                {
                    e.printStackTrace();
                }

            }
        }

    }
}
